using Microsoft.Extensions.DependencyInjection;
using UwinEducation.Application.Common.Interfaces;

namespace UwinEducation.Application.Common.Helpers
{
    /// <summary>
    /// 服务定位器，用于在静态上下文中访问服务
    /// </summary>
    public static class ServiceLocator
    {
        private static IServiceProvider _serviceProvider;

        /// <summary>
        /// 初始化服务定位器
        /// </summary>
        public static void Initialize(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 获取服务
        /// </summary>
        public static T GetService<T>() where T : class
        {
            return _serviceProvider?.GetService<T>();
        }

        /// <summary>
        /// 获取配置值
        /// </summary>
        public static string GetConfigValue(string key, string defaultValue = null)
        {
            try
            {
                var configService = GetService<ISystemConfigService>();
                if (configService == null)
                    return defaultValue;

                var value = configService.GetValueByKeyAsync(key).Result;
                return string.IsNullOrEmpty(value) ? defaultValue : value;
            }
            catch
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// 获取整型配置值
        /// </summary>
        public static int GetConfigIntValue(string key, int defaultValue = 0)
        {
            var value = GetConfigValue(key);
            return int.TryParse(value, out int result) ? result : defaultValue;
        }
    }
} 